<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 回调信息
 * @ApiInternal
 */
class Notify extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = '*';

    /**
     * 微信支付回调
     */
    public function wechat()
    {
        $string = file_get_contents('php://input');
        $this->addLog("notify-wechat",$string);
        libxml_disable_entity_loader(true);
        if (preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $string)) {
            return false;
        }
        $obj = simplexml_load_string($string, "SimpleXMLElement", LIBXML_NOCDATA);
        $data = json_decode(json_encode($obj), true);
        if (empty($data)) {
            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => '',
            );
            echo \fast\Utils::array2xml($result);
            exit;
        }
        if ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS') {
            $result = array(
                'return_code' => 'FAIL',
                'return_msg' => empty($data['return_msg']) ? $data['err_code_des'] : $data['return_msg'],
            );
            echo \fast\Utils::array2xml($result);
            exit;
        }
        $model = new \app\common\library\Wechatpay();
        if(!$model->checkSign($data)){
            exit("FAIL");
        }
        $this->notify($data,"wechat");
        exit("SUCCESS");
    }
    public function _initialize()
    {
        parent::_initialize();
    }
    /**
     * 支付宝支付回调
     */
    public function alipay()
    {
        $data = $this->request->post();
        $this->addLog("notify-alipay",$data);
        if (empty($data['trade_status']) || !in_array($data['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
            exit("fail");
        }
        $data['transaction_id'] = $data['trade_no'];
        $model = new \app\common\library\Alipay();
        if(!$model->checkSign($data,$data['sign'])){
            exit("fail");
        }
        $this->notify($data,"alipay");
        exit("success");
    }
    /**
     * 支付回调
     */
    public function notify($data,$payType)
    {
        $this->addLog("notify-".$payType,$data);
        Db::startTrans();
        try {
            if (strpos($data['out_trade_no'], 'agent') !== false) {
                \app\admin\model\agent\Order::agentPay($data['out_trade_no'], $data['transaction_id'], $payType);
            } elseif (strpos($data['out_trade_no'], 'pt') !== false) {
                \app\admin\model\SpellOrder::startPay($data['out_trade_no'], $data['transaction_id'], $payType);
            }
        }catch (\Exception $e){
            Db::rollback();
            $this->addLog("notify-err-".$payType,$e->getMessage());
            return false;
        }
        Db::commit();
        return true;
    }
}
